package com.aabte.nettyleran.netty.serial.marshalling;

import com.aabte.nettyleran.netty.serial.protobuf.proto.SubscribeReqProto;
import com.aabte.nettyleran.netty.serial.protobuf.proto.SubscribeRespProto;
import com.aabte.nettyleran.util.MarshallingCodecFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/13
 */
public class SubReqClient {

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        new SubReqClient().connect("127.0.0.1", port);
    }

    public void connect(String host, int port) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(MarshallingCodecFactory.buildMarshallingDecoder());
                        socketChannel.pipeline().addLast(MarshallingCodecFactory.buildMarshallingEncoder());
                        socketChannel.pipeline().addLast(new SubReqClientHandler());
                    }
                });

        try {
            // 发起异步连接操作
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            // 等待客户端链路关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放NIO线程组
            group.shutdownGracefully();
        }
    }

    /**
     * @author Daniel
     * @version 1.0
     * @date 2020/3/13
     */
    public static class SubReqClientHandler extends ChannelHandlerAdapter {

        public SubReqClientHandler() {
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            for (int i = 0; i < 10; i++) {
                ctx.writeAndFlush(subReq(i));
            }
        }

        private SubscribeReqProto.SubscribeReq subReq(int id) {
            return SubscribeReqProto.SubscribeReq.newBuilder()
                    .setSubReqId(id)
                    .setUsername("tom")
                    .setProductName("netty book for marshalling")
                    .setAddress("lota")
                    .build();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            SubscribeRespProto.SubscribeResp response = (SubscribeRespProto.SubscribeResp) msg;
            System.out.println("Receive server response: \n" + response);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
}
